<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <div class="structure_cent_b">
          <!-- <div class="structure_cent_b_left">
            <a-tree
              :tree-data="bumentreeData"
              :replaceFields='replaceFields'
              @select='clicktree'
              :default-selected-keys="defaultselected"
            ></a-tree>
          </div> -->
          <div class="structure_cent_b_right">
            <div class="structure_cent_b_title">
              <a-button
                  v-action:add
                  type='primary'
                  @click="adduser"
              >新增
              </a-button>
              <div style="margin-top:20px;display:flex">
                <a-input
                    style="flex:1"
                    v-model.trim="searchuser.name"
                    placeholder="请输入名称"
                    allowClear
                />
                <a-input
                    v-model.trim="searchuser.account "
                    placeholder="请输入邮箱/手机号/账号"
                    style="flex:1;margin-left:20px"
                    allowClear
                />
                <a-tree-select
                    style="flex:1;margin-left:20px"
                    allow-clear
                    :tree-data="treeData"
                    placeholder="选择公司"
                    :show-checked-strategy="SHOW_PARENT"
                    :replaceFields='replaceFields'
                    @change='selectgongsitree1'
                />
                <a-button
                    type='danger'
                    style="margin-left:20px;width:130px"
                    @click="search"
                >查找人员
                </a-button>
              </div>
            </div>
            <a-table
                :columns="columns"
                :data-source="datalist"

                rowKey="id"
                :pagination="false"
                :scroll="{ x:true}"
            >
              <template
                  slot="status"
                  slot-scope="text"
              >
                {{ yingjilist[text] }}
              </template>
              <template
                  slot="mobile"
                  slot-scope="text,record"
              >
                <span v-if="text">{{ text }}</span>
                <span
                    style="margin-left:10px"
                    v-if='record.email'
                >{{ record.email }}</span>
              </template>

              <span
                  slot='googleVerifyEnableStatus'
                  slot-scope='text,record'
              >
                <a-switch
                    v-action:changeGoogleStatus
                    v-if="record.googleVerifyStatus==1"
                    :checked="text==1?true:false"
                    checked-children="启用"
                    un-checked-children="禁用"
                    @change="switchChange(record.id)"
                />
              </span>

              <template
                  slot="操作"
                  slot-scope="text, record"
              >
                 <a
                     v-action:assigningRoles
                  href="javascript:;"
                  style="margin-left:10px"
                  @click="$refs.AssigningRoleModal.open(record)"
                >分配角色</a>
                <a
                    v-action:edit
                    href="javascript:;"
                    style="margin-left:10px"
                    @click="bianji(record)"
                >编辑</a>
                <a
                    v-action:resetPassword
                    href="javascript:;"
                    style="margin-left:10px"
                    @click="reset(record)"
                >重置密码</a>
                <a-popconfirm
                    style="margin-left:10px"
                    cancelText='取消'
                    okText="确认"
                    title="您确定要删除吗?"
                    @confirm="onDelete(record)"
                >
                  <a
                      v-action:del
                      href="javascript:;"
                  >删除</a>
                </a-popconfirm>
              </template>
            </a-table>
            <a-pagination
                show-quick-jumper
                :defaultPageSize='1'
                :current='query.pageNo'
                :total="totalnum"
                @change="onChange1"
                style=" margin-top:15px;text-align:right"
            />
          </div>
        </div>
      </div>

      <!-- 新增人员 -->
      <a-modal
          :title="usertitle"
          :visible="visible"
          :confirm-loading="confirmLoading"
          @ok="handleOk"
          @cancel="handleCancel"
          :destroyOnClose='true'
          cancel-text="取消"
          ok-text="确定"
          :scroll="{ x:true}"
      >
        <a-form
            :form="form"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 12 }"
            @submit="handleOk"
        >
          <a-form-item label="人员姓名">
            <a-input
                allowClear
                placeholder="请输入人员姓名"
                v-decorator="['name', { rules: [{ required: true, message: '请输入人员姓名' }] }]"
            />
          </a-form-item>
          <a-form-item label="联系电话">
            <a-input
                allowClear
                placeholder="请输入联系电话"
                v-decorator="['mobile', { rules: [{ required: true, message: '请输入联系电话' }] }]"
            />
          </a-form-item>
          <a-form-item label="登录账号">
            <a-input
                allowClear
                placeholder="请设置人员登录账号"
                v-decorator="['account', { rules: [{ required: true, message: '请设置人员登录账号' }] }]"
            />
          </a-form-item>
          <a-form-item
              label="登录密码"
              v-if="bianjitype!=1"
          >
            <a-input-password
                allowClear
                placeholder="请设置人员登录密码"
                v-decorator="['password', { rules: [{ required: true, message: '请设置人员登录密码' }] }]"
            />
          </a-form-item>
          <a-form-item label="选择角色">
            <a-select
                allowClear
                mode="multiple"
                placeholder="请选择角色"
                v-decorator="['roleIds', { rules: [{ required: false, message: '请选择角色' }] }]"
            >
              <a-select-option
                  v-for="item in jueseData"
                  :key="item.id"
              >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <!--          <a-form-item label="选择公司">
                      <a-tree-select
                        allowClear
                        v-decorator="[
                              'detpIds',
                              { rules: [{ required: false, message: '请选择公司' }] },
                            ]"
                        style="width: 100%"
                        :tree-data="treeData"
                        tree-checkable
                        :treeCheckStrictly='true'
                        placeholder="请选择公司"
                        :replaceFields='replaceFields'
                        @change='selectusertree'
                      />
                    </a-form-item>-->
        </a-form>
      </a-modal>
      <!-- 查看人员 -->
      <!-- <a-modal
        :title="usertitle"
        :visible="visible1"
        :destroyOnClose='true'
        @ok="handleCancel"
        @cancel="handleCancel"
        width='800px'
        cancel-text="取消"
        ok-text="确定"
        :scroll="{ x:true}"
      >
        <div class="userinfo">
          <ul class="ul1">
            <li>姓名：{{userinfo.name}}</li>
            <li>手机号：{{userinfo.mobile}}</li>
            <li>角色列表：{{userinfo.roleName}}</li>
          </ul>
          <p class="userinfo_title">参与抢险救援统计</p>
          <a-table
            :columns="columns1"
            :data-source="userinfolist"
            bordered
             rowKey="id"
            :pagination="false"
          >
          </a-table>
          <a-pagination
            show-quick-jumper
            :defaultPageSize='1'
            :current='yeshu1'
            :total="totalnum1"
            @change="onChange2"
            style=" margin-top:15px;text-align:right;"
          />

        </div>
      </a-modal> -->
    </a-card>
    <AssigningRoleModal ref="AssigningRoleModal" @change="getuserlistOnly"/>
  </page-header-wrapper>
</template>


<script>
import {
  getTree,
  adduser,
  adddepartment,
  getuser,
  addgongsi,
  gongsiTree,
  getgongsi,
  getbumen,
  deleteuser,
  getuserlist,
  resetpassword,
  getxianqing,
  xiazai,
  editGoogleVerifyEnable,
} from "@/api/structure";
import {TreeSelect} from "ant-design-vue";
import {getTreeData, getchild} from "@/utils/util";
import md5 from "md5";
import {urlspath} from "@/utils/util";
import storage from "store";
import AssigningRoleModal from "@/views/admin/system/module/assigningRoleModal";

const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const columns1 = [
  {
    title: "时间",
    dataIndex: "createTime",
    align: "center",
  },
  {
    title: "救援事件",
    dataIndex: "content",
    align: "center",
    width: 300,
  },
  {
    title: "地址",
    dataIndex: "address",
    align: "center",
  },
  {
    title: "险情等级",
    dataIndex: "emergencyInfoVO.level",
    align: "center",
  },
];
const columns = [
  {
    title: "创建时间",
    dataIndex: "createTime",
    align: "center",
  },
  {
    title: "名称",
    dataIndex: "name",
    align: "center",
  },
  {
    title: "手机号/邮箱",
    dataIndex: "mobile",
    align: "center",
    scopedSlots: {customRender: "mobile"},
  },
  {
    title: "账号",
    dataIndex: "account",
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "status",
    align: "center",
    scopedSlots: {customRender: "status"},
  },
  /*  {
      title: "谷歌验证",
      dataIndex: "googleVerifyEnableStatus",
      align: "center",
      scopedSlots: { customRender: "googleVerifyEnableStatus" },
    },*/
  {
    title: "操作",
    fixed: "right",
    dataIndex: "operation",
    scopedSlots: {customRender: "操作"},
    // align: "center",
  },
];
export default {
  components: {
    AssigningRoleModal
  },
  data() {
    return {
      tokenId: "",
      urls: "",
      userinfolist: [],
      userinfo: "",
      visible1: false,
      SHOW_PARENT,
      visible: false,
      confirmLoading: false,
      replaceFields: {
        children: "childList",
        title: "name",
        key: "id",
        value: "id",
      },
      usertitle: "",
      datalist: [],
      treeData: [],
      bumentreeData: [],
      bianjitype: 0,
      columns,
      columns1,
      bianjiId: "",
      defaultselected: [],
      searchuser: {
        name: "",
        account: "",
      },
      form: this.$form.createForm(this, {name: "coordinated"}),
      userarr: [],
      typeId: 0,
      bumenarr: "",
      totalnum1: 0,
      yeshu1: 1,
      totalnum: 0,
      yingjilist: ["正常", "禁用"],
      treeid: "",
      ttype: "",
      jueseData: [],

      query: {
        pageNo: 1,
        pageSize: 10,
        organizationIds: "",
      },
    };
  },
  mounted() {
    this.urls = urlspath;
    // this.tokenId = storage.get("userInfo").tokenId;
    this.getbumenTree();
    this.getgongsiTree();
    this.getjuese();
    this.getuserlistOnly();
  },
  methods: {
    //查看人员详情
    views(val) {
      this.usertitle = "人员详情";
      this.userinfo = val;

      this.getuserxiang();
      this.visible1 = true;
      console.log(val);
    },

    async getuserxiang() {
      let res = await getxianqing({
        userId: this.userinfo.id,
        pageNo: this.yeshu1,
        pageSize: 5,
      });
      if (res.code == 0) {
        this.userinfolist = res.data.records;
        this.totalnum1 = res.data.pages;
      }
    },
    //获取角色列表
    async getjuese() {
      let res = await getuserlist();
      if (res.code == 0) {
        this.jueseData = res.data;
      }
    },
    //获取公司树
    async getgongsiTree() {
      let res = await gongsiTree();
      if (res.code == 0) {
        this.treeData = res.data;
        this.defaultselected = [];
        this.defaultselected.push(this.treeData[0].id);
      }
    },
    //获取单独人员列表
    async getuserlistOnly() {
      let res = await getuser({
        pageNo: this.query.pageNo,
        pageSize: this.query.pageSize,
        name: this.searchuser.name,
        account: this.searchuser.account,
        organizationId: this.treeid,
        organizationIdType: this.ttype,
      });
      if (res.code == 0) {
        this.datalist = res.data.records;
        this.totalnum = res.data.pages;
      }
    },
    //获取人员列表
    async getuserlist(val, page) {
      let res = await getuser({
        pageNo: this.query.pageNo,
        pageSize: this.query.pageSize,
        name: this.searchuser.name,
        account: this.searchuser.account,
        // organizationIds:  this.query.organizationIds,
        organizationId: this.treeid,
        organizationIdType: this.ttype,
      });
      if (res.code == 0) {
        this.datalist = res.data.records;
        this.totalnum = res.data.pages;
      }
    },
    //获取公司部门树
    async getbumenTree() {
      let res = await getTree();
      if (res.code == 0) {
        this.bumentreeData = res.data;
        this.defaultselected = [];
        this.defaultselected.push(this.bumentreeData[0].id);
      }
    },
    //点击人组织架构树
    clicktree(val, e) {
      console.log("值", val);
      this.query.pageNo = 1;
      this.defaultselected = [];
      this.defaultselected.push(val[0]);
      console.log(this.defaultselected);
      let res = getTreeData(this.defaultselected, this.treeData);
      if (res.length > 0) {
        this.ttype = res[0].type;
        this.getuserlist(val[0], 1);
      } else {
        this.ttype = 0;
        this.getuserlist(0, 1);
      }
    },
    //查找人员
    search() {
      console.log(this.searchuser);
      this.query.pageNo = 1;
      this.getuserlist();
    },
    //重置密码
    async reset(val) {
      let res = await resetpassword({userId: val.id});
      if (res.code == 0) {
        this.$notification.success({
          message: "成功",
          description: "重置密码成功",
        });
        this.getuserlist();
      }
    },
    //删除
    async onDelete(val) {
      let res = await deleteuser({id: val.id});
      if (res.code == 0) {
        this.$notification.success({
          message: "成功",
          description: "删除成功",
        });
        this.getuserlist();
      }
    },

    //新增人员
    adduser() {
      this.bianjitype = 0;
      this.usertitle = "新增人员信息";
      this.visible = true;
    },
    //编辑
    bianji(val) {
      console.log(val);
      this.bianjitype = 1;
      this.visible = true;
      this.bianjiId = val.id;
      this.usertitle = "编辑人员信息";
      let arr = [];
      if (val.compIds != undefined && val.compIds.length > 0) {
        let res = getTreeData(val.compIds.split(","), this.bumentreeData);
        res.forEach((item) => {
          arr.push({
            value: item.id,
            label: item.name,
          });
        });
      }

      if (val.roleIds) {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            name: val.name,
            mobile: val.mobile,
            account: val.account,
            // detpIds: arr,
            roleIds: val.roleIds.split(","),
          });
        });
      } else {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            name: val.name,
            mobile: val.mobile,
            account: val.account,
            // detpIds: arr,
          });
        });
      }
    },
    //选择人员树
    selectusertree(value, label, extra) {
      this.userarr = [];
      let userid = [];
      if (value.length != 0) {
        value.forEach((item) => {
          userid.push(item.value);
        });
        this.userarr = getTreeData(userid, this.treeData);
      }
      console.log(this.userarr);
    },
    //提交新增人员
    handleOk(e) {
      e.preventDefault();
      this.form.validateFields(async (err, values) => {
        if (!err) {
          let data;
          this.confirmLoading = true;
          if (this.bianjitype == 1) {
            data = {
              name: values.name,
              mobile: values.mobile,
              account: values.account,
              organList: [],
              id: this.bianjiId,
              roleIds: values.roleIds.join(","),
            };
          } else if (this.bianjitype == 0) {
            data = {
              name: values.name,
              mobile: values.mobile,
              account: values.account,
              organList: [],
              password: md5(values.password),
              roleIds: values.roleIds.join(","),
            };
          }
          this.userarr.forEach((item) => {
            data.organList.push({
              id: item.id,
              type: item.type,
            });
          });

          data.organList = JSON.stringify(data.organList);
          console.log(data);
          let res = await adduser(data);
          if (res.code == 0) {
            this.$notification.success({
              message: "成功",
              description: "提交成功",
            });
            this.getbumenTree();
            this.getgongsiTree();
            this.getuserlistOnly();
            this.confirmLoading = false;
            this.visible = false;
          } else {
            this.confirmLoading = false;
          }
        }
      });
    },

    //选择部门树
    selecttree(value, label, extra) {
      this.bumenarr = "";
      let arr = [];
      arr.push(value);
      console.log("部门", value);
      console.log("部门", arr);
      this.bumenarr = getTreeData(arr, this.bumentreeData);
      console.log(this.bumenarr);
    },
    //选择公司树
    selectgongsitree(value, label, extra) {
      this.bumenarr = "";
      let arr = [];
      arr.push(value);
      console.log("公司", value);
      console.log("公司", arr);
      this.bumenarr = getTreeData(arr, this.treeData);
      console.log(this.bumenarr);
    },
    selectgongsitree1(value, label, extra) {
      console.log(111, value);
      if (value) {
        let res = getTreeData([value], this.treeData);
        this.treeid = value;
        this.ttype = res[0].type;
      } else {
        this.treeid = "";
        this.ttype = "";
      }
    },
    //取消弹窗
    handleCancel(e) {
      this.visible = false;
      this.visible1 = false;
      this.confirmLoading = false;
      this.yeshu1 = 1;
    },
    onChange1(pageNumber) {
      this.query.pageNo = pageNumber;
      this.getuserlist();
    },
    onChange2(pageNumber) {
      this.yeshu1 = pageNumber;
      this.getuserxiang();
    },
    // 启用禁用谷歌验证
    async switchChange(id, statuss) {
      let res = await editGoogleVerifyEnable({id: id});
      if (res.code == 0) {
        this.$message.success(res.msg);
        this.getuserlist();
      }
    },
  },
};
</script>

<style scoped>
.userinfo {
}

.ul1 li {
  margin-bottom: 10px;
}

.userinfo_title {
  font-size: 16px;
  text-align: center;
}

.ul1 {
  padding: 0;
  font-size: 16px;
  border-bottom: 1px solid #ccc;
}

.structure_cent {
  background: #fff;
  border: 1px solid #ccc;
}

.structure_cent_title {
  width: 100%;
  font-size: 16px;
  color: #333;
  background: #f6f6f6;
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  border-bottom: 1px solid #ccc;
}

.structure_cent_title span {
  border-left: 4px solid #0086ff;
  padding-left: 15px;
}

.structure_cent_b {
  /* max-width: 1200px; */
  /* margin: auto; */
  /* display: flex; */
  /* justify-content: space-between; */
}

.structure_cent_b_left {
  width: 300px;
  min-width: 130px;
  border: 1px solid #ccc;
}

.structure_cent_b_right {
  /* width: 800px;  */
  /* margin-left: 20px; */
  /* position: relative; */
}

.structure_cent_b_title {
  margin-bottom: 30px;
}

.addbtn_f {
  width: 400px;
  display: flex;
  justify-content: space-between;
}

.addbtn_f div {
  width: 100px;
  height: 35px;
  border: 1px solid #ccc;
  text-align: center;
  line-height: 35px;
  font-size: 13px;
  color: #333;
  cursor: pointer;
  background: #f2f2f2;
}

.addbtn_f div:hover {
  background: #0086ff;
  color: #fff;
}
</style>